import java.util.PriorityQueue;
import java.util.concurrent.PriorityBlockingQueue;

class MyTimer{

    static class Task implements  Comparable<Task>{
        private Runnable runnable;
        private long time;

        public Task(Runnable runnable, long after) {
            this.runnable = runnable;
            this.time = System.currentTimeMillis()+after;
        }

        public void run(){
            runnable.run();
        }

        @Override
        public int compareTo(Task o) {
            return (int)(this.time-o.time);
        }
    }

    private PriorityBlockingQueue<Task> tasks=new PriorityBlockingQueue<>();

    public void schedule(Runnable runnable,long after){
        Task task=new Task(runnable,after);
        tasks.put(task);
    }

    private Object locker=new Object();


    public MyTimer(){
        Thread t=new Thread(()->{
            while (true){
                try {
                    Task task=tasks.take();
                    long curTime=System.currentTimeMillis();
                    if(task.time>=curTime){
                        synchronized (locker){
                            locker.wait(task.time-curTime);
                        }
                        tasks.put(task);
                    }else{
                        task.run();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }
}

public class Demo2 {
    public static void main(String[] args) {
        MyTimer myTimer=new MyTimer();

    }

}
